package com.example.hrsystem.ui.attendance;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;

import com.example.hrsystem.R;
import com.example.hrsystem.data.model.AttendanceRecord;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.Priority;
import com.google.android.gms.tasks.OnSuccessListener;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 打卡界面Activity
 * 提供签到签退功能
 */
public class AttendanceActivity extends AppCompatActivity {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private AttendanceViewModel attendanceViewModel;
    private TextView currentTimeTextView;
    private TextView checkInTimeTextView;
    private TextView checkOutTimeTextView;
    private TextView currentLocationTextView;
    private Button checkInButton;
    private Button checkOutButton;
    private Location currentLocation;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
    private FusedLocationProviderClient fusedLocationClient;
    private LocationRequest locationRequest;
    private LocationCallback locationCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attendance);

        // 初始化UI组件
        initUI();

        // 初始化ViewModel
        attendanceViewModel = new ViewModelProvider(this).get(AttendanceViewModel.class);

        // 观察加载状态
        attendanceViewModel.getIsLoading().observe(this, isLoading -> {
            checkInButton.setEnabled(!isLoading);
            checkOutButton.setEnabled(!isLoading);
        });

        // 观察错误信息
        attendanceViewModel.getErrorMessage().observe(this, errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });

        // 观察今日打卡记录
        observeTodayAttendance();

        // 获取当前时间
        updateCurrentTime();

        // 初始化位置服务
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        createLocationRequest();
        createLocationCallback();

        // 请求位置权限
        requestLocationPermission();
    }

    /**
     * 初始化UI组件
     */
    private void initUI() {
        currentTimeTextView = findViewById(R.id.current_time_text_view);
        checkInTimeTextView = findViewById(R.id.check_in_time_text_view);
        checkOutTimeTextView = findViewById(R.id.check_out_time_text_view);
        currentLocationTextView = findViewById(R.id.current_location_text_view);
        checkInButton = findViewById(R.id.check_in_button);
        checkOutButton = findViewById(R.id.check_out_button);

        // 设置签到按钮点击事件
        checkInButton.setOnClickListener(v -> performCheckIn());

        // 设置签退按钮点击事件
        checkOutButton.setOnClickListener(v -> performCheckOut());
    }

    /**
     * 请求位置权限
     */
    private void requestLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            getCurrentLocation();
        }
    }

    /**
     * 创建位置请求
     */
    private void createLocationRequest() {
        locationRequest = new LocationRequest.Builder(
                Priority.PRIORITY_HIGH_ACCURACY,
                10000) // 10秒更新一次
                .setWaitForAccurateLocation(false)
                .setMinUpdateIntervalMillis(5000) // 最小更新间隔5秒
                .setMaxUpdateDelayMillis(10000) // 最大更新延迟10秒
                .build();
    }

    /**
     * 创建位置回调
     */
    private void createLocationCallback() {
        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                if (locationResult == null) {
                    return;
                }
                for (Location location : locationResult.getLocations()) {
                    updateLocationData(location);
                }
            }
        };
    }

    /**
     * 更新位置数据
     */
    private void updateLocationData(Location location) {
        currentLocation = location;
        String locationText = String.format("当前位置：纬度 %.6f, 经度 %.6f", 
                location.getLatitude(), location.getLongitude());
        currentLocationTextView.setText(locationText);
    }

    /**
     * 获取当前位置
     */
    private void getCurrentLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        
        // 获取最新位置
        fusedLocationClient.getLastLocation()
                .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        if (location != null) {
                            updateLocationData(location);
                        } else {
                            // 如果无法获取最后位置，启动位置更新请求
                            startLocationUpdates();
                            Toast.makeText(AttendanceActivity.this, "正在获取位置信息...", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    /**
     * 开始位置更新
     */
    private void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
    }

    /**
     * 停止位置更新
     */
    private void stopLocationUpdates() {
        if (locationCallback != null) {
            fusedLocationClient.removeLocationUpdates(locationCallback);
        }
    }

    /**
     * 更新当前时间
     */
    private void updateCurrentTime() {
        String currentTime = dateFormat.format(new Date());
        currentTimeTextView.setText("当前时间：" + currentTime);
    }

    /**
     * 观察今日打卡记录
     */
    private void observeTodayAttendance() {
        // 假设当前用户ID为"1001"
        attendanceViewModel.getTodayAttendanceRecord("1001").observe(this, record -> {
            if (record != null) {
                // 设置签到时间
                checkInTimeTextView.setText("签到时间：" + timeFormat.format(record.getCheckInTime()));
                checkInTimeTextView.setVisibility(View.VISIBLE);
                checkInButton.setEnabled(false);
                checkInButton.setText("已签到");

                // 设置签退时间
                if (record.getCheckOutTime() != null) {
                    checkOutTimeTextView.setText("签退时间：" + timeFormat.format(record.getCheckOutTime()));
                    checkOutTimeTextView.setVisibility(View.VISIBLE);
                    checkOutButton.setEnabled(false);
                    checkOutButton.setText("已签退");
                } else {
                    checkOutButton.setEnabled(true);
                }

                // 设置打卡类型
                // 可以根据需要显示打卡类型
            }
        });
    }

    /**
     * 执行签到操作
     */
    private void performCheckIn() {
        if (currentLocation != null) {
            // 假设当前用户ID为"1001"
            // 实际应用中应该从用户信息中获取
            String location = String.format("纬度: %.6f, 经度: %.6f", 
                    currentLocation.getLatitude(), currentLocation.getLongitude());
            attendanceViewModel.checkIn("1001", location);
        } else {
            Toast.makeText(this, "请先获取位置信息", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 执行签退操作
     */
    private void performCheckOut() {
        if (currentLocation != null) {
            // 假设当前用户ID为"1001"
            // 实际应用中应该从用户信息中获取
            String location = String.format("纬度: %.6f, 经度: %.6f", 
                    currentLocation.getLatitude(), currentLocation.getLongitude());
            attendanceViewModel.checkOut("1001", location);
        } else {
            Toast.makeText(this, "请先获取位置信息", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理权限请求结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getCurrentLocation();
            } else {
                Toast.makeText(this, "需要位置权限才能打卡", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 更新当前时间
        updateCurrentTime();
        // 获取当前位置
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            getCurrentLocation();
            startLocationUpdates(); // 在恢复时继续位置更新
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 在暂停时停止位置更新以节省电量
        stopLocationUpdates();
    }
}